﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a time stamp object write transfer
    /// </summary>
    public class TimeStampObjectWriteTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isProducerTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private TimeStampObjectReceivedEventHandler _timeStampObjectReceivedEventHandler;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default producer COB-ID
        /// </summary>
        static public readonly UInt16 DefaultProducerCobId = 0x100;


        /// <summary>
        /// Initializes a new instance of the TimeStampObjectWriteTransfer class
        /// by the given parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="timeStampObjectReceivedEventHandler">
        /// Time stamp object received event handler (or null)
        /// </param>
        private TimeStampObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, TimeStampObjectReceivedEventHandler timeStampObjectReceivedEventHandler)
        {
            _isProducerTransfer = false;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _timeStampObjectReceivedEventHandler = timeStampObjectReceivedEventHandler;
        }

        /// <summary>
        /// Initializes a new instance of the TimeStampObjectWriteTransfer class
        /// by the given parameter
        /// </summary>
        /// <param name="days">
        /// Time stamp days to send with the time stamp object
        /// </param>
        /// <param name="milliseconds">
        /// Time stamp milliseconds to send with the time stamp object
        /// </param>
        public TimeStampObjectWriteTransfer(UInt16 days, uint milliseconds)
            : this(days, milliseconds, DefaultProducerCobId)
        {
        }

        /// <summary>
        /// Initializes a new instance of the TimeStampObjectWriteTransfer class
        /// by the given parameter
        /// </summary>
        /// <param name="days">
        /// Time stamp days to send with the time stamp object
        /// </param>
        /// <param name="milliseconds">
        /// Time stamp milliseconds to send with the time stamp object
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        public TimeStampObjectWriteTransfer(UInt16 days, uint milliseconds, UInt16 producerCobId)
        {
            _isProducerTransfer = true;
            ProducerCobId = producerCobId;
            TimeStamp = new CanOpenTimeOfDay(0, 0, true, true) { Days = days, Milliseconds = milliseconds };
        }


        /// <summary>
        /// Gets or sets the time stamp
        /// </summary>
        private CanOpenTimeOfDay TimeStamp
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the producer COB-ID
        /// </summary>
        private UInt16 ProducerCobId
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a time stamp object
        /// write transfer request and if so it returns as out parameter a
        /// matching time stamp object write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="timeStampObjectWriteTransfer">
        /// A matching time stamp object write transfer instance
        /// </param>
        /// <param name="timeStampObjectReceivedEventHandler">
        /// Time stamp object received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a time stamp object write
        /// transfer request, false otherwise
        /// </returns>
        static public bool IsTimeStampObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, out TimeStampObjectWriteTransfer timeStampObjectWriteTransfer, TimeStampObjectReceivedEventHandler timeStampObjectReceivedEventHandler)
        {
            return IsTimeStampObjectWriteTransfer(receivedCanOpenMessage, out timeStampObjectWriteTransfer, DefaultProducerCobId, timeStampObjectReceivedEventHandler);
        }

        /// <summary>
        /// Checks if the given received can open message is a time stamp object
        /// write transfer request and if so it returns as out parameter a
        /// matching time stamp object write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="timeStampObjectWriteTransfer">
        /// A matching time stamp object write transfer instance
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        /// <param name="timeStampObjectReceivedEventHandler">
        /// Time stamp object received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a time stamp object write
        /// transfer request, false otherwise
        /// </returns>
        static public bool IsTimeStampObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, out TimeStampObjectWriteTransfer timeStampObjectWriteTransfer, UInt16 producerCobId, TimeStampObjectReceivedEventHandler timeStampObjectReceivedEventHandler)
        {
            // check parameter
            if (receivedCanOpenMessage == null)
            {
                timeStampObjectWriteTransfer = null;
                return false;
            }

            // check COB-ID
            if (receivedCanOpenMessage.CanId != producerCobId)
            {
                timeStampObjectWriteTransfer = null;
                return false;
            }

            // create transfer instance
            timeStampObjectWriteTransfer = new TimeStampObjectWriteTransfer(receivedCanOpenMessage, timeStampObjectReceivedEventHandler);
            return true;
        }

        /// <summary>
        /// Starts the producer transfer
        /// </summary>
        private void startProducerTransfer()
        {
            UInt16 canId = ProducerCobId;
            IList<byte> byteArray = (TimeStamp as ICanOpenValueObject).ToByteArray();
            byte byte0 = (byteArray.Count > 0 ? byteArray[0] : (byte)0);
            byte byte1 = (byteArray.Count > 1 ? byteArray[1] : (byte)0);
            byte byte2 = (byteArray.Count > 2 ? byteArray[2] : (byte)0);
            byte byte3 = (byteArray.Count > 3 ? byteArray[3] : (byte)0);
            byte byte4 = (byteArray.Count > 4 ? byteArray[4] : (byte)0);
            byte byte5 = (byteArray.Count > 5 ? byteArray[5] : (byte)0);
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, byte1, byte2, byte3, byte4, byte5, 0x00, 0x00, 6));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Starts the consumer transfer
        /// </summary>
        private void startConsumerTransfer()
        {
            // process data
            if (_timeStampObjectReceivedEventHandler != null)
            {
                CanOpenTimeOfDay timeStamp = new CanOpenTimeOfDay(0, 0, true, true);
                List<byte> byteArray = new List<byte>() { _receivedCanOpenMessage.Byte0, _receivedCanOpenMessage.Byte1, _receivedCanOpenMessage.Byte2, _receivedCanOpenMessage.Byte3, _receivedCanOpenMessage.Byte4, _receivedCanOpenMessage.Byte5 };
                (timeStamp as ICanOpenValueObject).FromByteArray(byteArray);
                _timeStampObjectReceivedEventHandler(this, new TimeStampObjectReceivedEventArgs(timeStamp.Days, timeStamp.Milliseconds));
            }

            // end transfer
            TransferComplete = true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isProducerTransfer)
            {
                startProducerTransfer();
            }
            else
            {
                startConsumerTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            return false;
        }
        #endregion ITransfer implementation

    }

}
